const { app, BrowserWindow, ipcMain } = require('electron')
const path = require('node:path')
const fastcsv = require('fast-csv');
const fs = require('fs')
const csv = require('csv-parser')
const { getRuleResult, runRule, getLogData, getJobList, getDetail, getJobPath, updateSubmitStatus,
  updateJobCategory
 } = require('./src/apis')

const CSV_FILENAME = getJobPath()

function createWindow () {
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js')
    }
  })

  // win.loadFile('index.html')
  win.loadURL('http://localhost:3000/')

  // 更新职位进度
  ipcMain.on('message-update-submit-status', (event, req) => {
    console.log('message-update-submit-status')
    updateSubmitStatus(req).then((results) => {
      event.reply('response-update-submit-status', results)
    })
  })

  // 更新职位信息
  ipcMain.on('message-update-job-category', (event, req) => {
    console.log('message-update-job-category', req)
    updateJobCategory(req).then((results) => {
      event.reply('response-update-job-category', results)
    })
  })


  // 获取采集数据
  ipcMain.on('message-get-collect-data', (event, req) => {
    console.log('message-get-collect-data')
    getRuleResult('rule_main_areas', req).then((results) => {
      event.reply('response-get-collect-data', results)
    })
  })

  // 执行采集操作
  ipcMain.on('message-run-collect-rule', (e, req) => {
    console.log('message-run-collect-rule', req)
    runRule('rule_main_areas', req).then((res)=>{
      e.reply('response-run-collect-rule', res.result)
    })
  })

  // 获取采集日志
  ipcMain.on('message-get-log', (event, req) => {
    getLogData().then((results) => {
      event.reply('response-get-log', results)
    })
  })

  // 获取职位列表
  ipcMain.on('message-get-job-list', (event, req) => {
    console.log('message-get-job-list', req)
    getJobList().then((results)=>{
      event.reply('response-get-job-list', results)
    })
  })

  // 获取职位详情
  ipcMain.on('message-get-job-description', (event, req) => {
    getDetail(req).then((result)=> {
      event.reply('response-get-job-description', result)
    })
  })

  const deleteJobSoft = (event, ids_to_delete) => {
    const newRows = []

    fs.createReadStream(CSV_FILENAME)
    .pipe(csv())
    .on('data', (row) => {
      
      if (ids_to_delete.includes(row['编号'])) {
        row['状态'] = '已删除'
      }
      newRows.push(row) 
    })
    .on('end', () => { 
      const csvStream = fastcsv.format({ headers: true });
      csvStream.pipe(fs.createWriteStream(CSV_FILENAME,{
        flags: 'w', 
        encoding: 'utf8',
        autoClose: true
      }));

      newRows.forEach((row) => {
        csvStream.write(row);
      });
      
      csvStream.end();
  
      event.reply('response-delete-job-list', {data : newRows.filter(row => row['状态'] != '已删除')})
    })
    .on('error', (err) => {
      console.error(`读取文件时出错: ${err.message}`);
    });
  }

  const deleteJobHard = (event, ids) => {
    const newRows = []
    fs.createReadStream(CSV_FILENAME)
    .pipe(csv())
    .on('data', (row) => {
      if (!ids.includes(row['编号'])) {
        newRows.push(row)
      }
    })
    .on('end', () => {
      console.log('处理完成。检查 data_origin.csv 文件。');
      console.log(newRows.length)
      const csvStream = fastcsv.format({ headers: true });
      csvStream.pipe(fs.createWriteStream(CSV_FILENAME,{
        flags: 'w', 
        encoding: 'utf8',
        autoClose: true
      }));

      newRows.forEach((row) => {
        csvStream.write(row);
      });
      
      csvStream.end();
      event.reply('response-delete-job-list', {data : newRows.filter(row => row['状态'] != '已删除')})
    })
    .on('error', (err) => {
      console.error(`读取文件时出错: ${err.message}`);
    })
  }

  // 批量删除职位
  ipcMain.on('message-delete-job-list', (event, req) => {
    console.log('message-delete-job-list')
    console.log(req)
    const { ids, hard } = req

    if (hard) {
      deleteJobHard(event, ids)
    } else {

      deleteJobSoft(event, ids)
    }
  })

  // 更新职位状态
  ipcMain.on('message-update-job-status', (event, req) => {
    console.log('message-update-job-status')
    const newRows = []
    const { ids_to_update, newStatus } = req

    fs.createReadStream(CSV_FILENAME)
    .pipe(csv())
    .on('data', (row) => {
      if (ids_to_update.includes(row['编号'])) {
        row['状态'] = newStatus
      }
      newRows.push(row)
    })
    .on('end', () => { 
      // console.log(newRows)
      const csvStream = fastcsv.format({ headers: true });
      csvStream.pipe(fs.createWriteStream(CSV_FILENAME,{
        flags: 'w', 
        encoding: 'utf8',
        autoClose: true
      }));

      newRows.forEach((row) => {
        csvStream.write(row);
      });
      
      csvStream.end();
  
      event.reply('response-update-job-status', {data : newRows})
    })
    .on('error', (err) => {
      console.error(`读取文件时出错: ${err.message}`);
    });
  })
}

app.whenReady().then(() => {
  createWindow()

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow()
    }
  })
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})